package org.amphiprion.diceroller.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.amphiprion.diceroller.ApplicationConstants;
import org.amphiprion.diceroller.dao.db.GamePresetDao;
import org.amphiprion.diceroller.entity.GamePreset;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class DiceRollerService extends Service {
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {

	}

	@Override
	public void onStart(Intent intent, int startid) {
		Log.d(ApplicationConstants.PACKAGE, "Service DiceRoller called: " + intent.getAction() + "  callback:" + intent.getStringExtra("CALLBACK_ACTION"));
		if ("org.amphiprion.diceroller.GetGames".equals(intent.getAction())) {
			final ArrayList<String> files = new ArrayList<String>();
			ArrayList<String> gameNames = new ArrayList<String>();
			String[] dirs = new File(ApplicationConstants.ROOT_DIRECTORY + "/games").list();
			for (int i = 0; i < dirs.length; i++) {
				File f = new File(ApplicationConstants.ROOT_DIRECTORY + "/games/" + dirs[i] + "/game-definition.xml");
				if (f.exists()) {
					gameNames.add(dirs[i]);
					files.add(ApplicationConstants.ROOT_DIRECTORY + "/games/" + dirs[i]);
				}
			}
			String[] titles = new String[files.size()];
			titles = gameNames.toArray(titles);
			String[] paths = new String[files.size()];
			paths = files.toArray(paths);

			Intent intentResp = new Intent();
			intentResp.putExtra("GAME_NAMES", titles);
			intentResp.putExtra("GAME_PATHS", paths);
			intentResp.setAction(intent.getStringExtra("CALLBACK_ACTION"));

			sendBroadcast(intentResp);
		} else if ("org.amphiprion.diceroller.GetPresets".equals(intent.getAction())) {
			String gameDir = intent.getStringExtra("GAME_PATH");
			List<GamePreset> presets = GamePresetDao.getInstance(getApplicationContext()).getPresets(gameDir);
			String[] ids = new String[presets.size()];
			String[] names = new String[presets.size()];
			for (int i = 0; i < presets.size(); i++) {
				GamePreset preset = presets.get(i);
				ids[i] = preset.getId();
				names[i] = preset.getName();
			}

			Intent intentResp = new Intent();
			intentResp.putExtra("PRESET_IDS", ids);
			intentResp.putExtra("PRESET_NAMES", names);
			intentResp.setAction(intent.getStringExtra("CALLBACK_ACTION"));

			sendBroadcast(intentResp);

		}
	}
}
